package com.ctrip.ec.api.admin.controller.goods;
import com.ctrip.ec.api.admin.model.query.QueryModel;
import com.ctrip.ec.biz.dao.image.ImageDao;
import com.ctrip.ec.dal.PagerSetting;
import com.ctrip.ec.api.admin.common.RequestContext;
import com.ctrip.ec.biz.dao.goods.GoodsImageDao;
import com.ctrip.ec.biz.entity.goods.GoodsImageEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.List;
@RestController
@RequestMapping("goodsImage")
public class GoodsImageController{
    @Autowired
    private GoodsImageDao goodsImage;

    @Value("${imageDomain}")
    private  String imageDomain;

    @Autowired
    private ImageDao image;


    @GetMapping("list")
    public List<GoodsImageEntity> list() throws SQLException {
        List<GoodsImageEntity> list = goodsImage.list();
        return list;
    }

    @PostMapping("list")
    public List<GoodsImageEntity> list(@RequestBody QueryModel model) throws  SQLException{
        PagerSetting setting = model.build();
        List<GoodsImageEntity> list = goodsImage.list(setting);
//        for (GoodsImageEntity entity : list){
//            entity.setImageUrl(imageDomain + entity.getImageUrl());
//        }
        RequestContext.setResponseHeaderCount(setting.getRecordCount());
        return list;
    }

    @GetMapping("detail/{id}")
    public  GoodsImageEntity detail(@PathVariable Long id) throws SQLException {
        return goodsImage.entity(id);
    }

    @PostMapping("save")
    public  Long save(@RequestBody GoodsImageEntity entity) throws SQLException {
        goodsImage.save(entity);
        image.inUse(entity.getImageId());
        return entity.getId();
    }

    @PostMapping("delete")
    public  void delete(@RequestBody List<Long> ids) throws SQLException {
        if(ids != null &&  ids.size()!= 0) {
            List<Long> imageIds = goodsImage.getImageIds(ids);
            if(imageIds!= null && imageIds.size()>0) {
                image.unUse(imageIds);
            }
            goodsImage.delete(ids);
        }
    }

    @PostMapping("erase")
    public void erase(@RequestBody List<Long> ids) throws  SQLException{
        goodsImage.erase(ids);
    }

    @PostMapping("unerase")
    public  void unerase(@RequestBody List<Long> ids) throws  SQLException{
        goodsImage.unerase(ids);
    }
}
